package com.test.ad.demo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.test.ad.demo.adapter.AdRecordAdapter;
import com.test.ad.demo.model.AdModel;
import com.test.ad.demo.util.AdCacheUtil;
import com.test.ad.demo.util.AppDataCleaner;
import com.test.ad.demo.util.DeviceInfoUtil;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 收益详情页：展示设备ID与日期、今日/本月预估收益，以及广告记录列表。
 */
public class EarningsActivity extends Activity {

    private AdCacheUtil adCacheUtil;
    private AdRecordAdapter adapter;
    private DecimalFormat decimalFormat;

    private Integer clearCount = 0;
    Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earnings);

        // 初始化工具类
        adCacheUtil = new AdCacheUtil(this);
        decimalFormat = new DecimalFormat("#.##");

        // 初始化视图
        initViews();
        
        // 加载数据
        loadData();
    }

    private void initViews() {
        TextView tvDeviceInfo = findViewById(R.id.tv_device_info);
        View back = findViewById(R.id.btn_back);
        TextView tvToday = findViewById(R.id.tv_today_income);
        TextView tvMonth = findViewById(R.id.tv_month_income);
        TextView tvCount = findViewById(R.id.tv_today_count);
        ListView listView = findViewById(R.id.list_records);
        ImageButton tvCleanBtn = findViewById(R.id.btn_clean_data);

        // 设置标题栏
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String date = sdf.format(new Date());
        String deviceId = DeviceInfoUtil.getAndroidId(this);
        tvDeviceInfo.setText(deviceId);

        // 设置返回按钮
        if (back != null) {
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        tvCleanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearCount += 1;
                if(toast != null) {
                    toast.cancel();
                }
                if(clearCount%2 != 0) {
                    toast = Toast.makeText(getApplicationContext(), "再点一次重置数据", Toast.LENGTH_SHORT);
                }
                else {
                    toast = Toast.makeText(getApplicationContext() , "已重置数据", Toast.LENGTH_SHORT);
                    adCacheUtil.clearAllAds();
                    AppDataCleaner.clearAllData(getApplicationContext());
                }
                if(toast != null) {
                    toast.show();
                }
                loadData();
            }
        });

        // 初始化列表适配器
        adapter = new AdRecordAdapter(this, new ArrayList<AdModel>());
        listView.setAdapter(adapter);
    }

    private void loadData() {
        // 获取所有广告数据
        List<AdModel> allAds = adCacheUtil.getAllAds();
        
        // 计算收益统计
        calculateEarnings(allAds);
        
        // 更新广告记录列表
        updateAdRecordList(allAds);
    }

    private void calculateEarnings(List<AdModel> allAds) {
        TextView tvToday = findViewById(R.id.tv_today_income);
        TextView tvMonth = findViewById(R.id.tv_month_income);
        TextView tvCount = findViewById(R.id.tv_today_count);

        // 获取今天的日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String today = simpleDateFormat.format(new Date());

        // 获取本月的第一天
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String monthStart = simpleDateFormat.format(calendar.getTime());

        double todayCoins = 0.0;
        double monthCoins = 0.0;
        int todayCount = 0;

        for (AdModel ad : allAds) {
            String adDate = ad.getDate();
            
            // 计算今日收益和次数
            if (today.indexOf(adDate.split(" ")[0]) > -1) {
                todayCoins += ad.getCoins();
                todayCount++;
            }
            
            // 计算本月收益
            if (adDate.compareTo(monthStart) >= 0 && adDate.compareTo(today) <= 0) {
                monthCoins += ad.getCoins();
            }
        }

        // 转换为元并显示（总/2）
        double todayYuan = todayCoins;
        double monthYuan = monthCoins;

        tvToday.setText(decimalFormat.format(todayYuan));
        tvMonth.setText(decimalFormat.format(monthYuan));
        tvCount.setText(new DecimalFormat("#").format(todayCount));
    }

    private void updateAdRecordList(List<AdModel> allAds) {
        // 按ID倒序排列（最新的在前面）
        List<AdModel> sortedAds = new ArrayList<>(allAds);
        sortedAds.sort((a, b) -> Integer.compare(b.getId(), a.getId()));
        
        adapter.updateData(sortedAds);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次回到页面时刷新数据
        loadData();
    }
}


